package com.example.testsbjenkins.jucTest;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @author: lt
 * @date: 2022/7/8 16:32
 * @Description: todo
 */
public class MyBlockingQueueForWaitNotify {

    private int max;
    private LinkedList<Object> storage;
    
    

    public MyBlockingQueueForWaitNotify(int max, LinkedList<Object> storage) {
        this.max = max;
        this.storage = new LinkedList<>();
    }

    public synchronized void put(Object o) throws InterruptedException {
        while (storage.size() == max) {
            System.out.println(Thread.currentThread().getName() + "队列满了,等待消费者线程消费元素");
            this.wait();
        }
        storage.add(o);
        System.out.println("新加入元素:"+o);
        this.notifyAll();
    }

    public synchronized Object take() throws InterruptedException {

        while (storage.size() == 0) {
            System.out.println(Thread.currentThread().getName()+"队列空了,取不出元素,等待生产者线程放入元素");
            this.wait();
        }
        Object remove = storage.remove();
        System.out.println("取出元素:" + remove);
        this.notifyAll();
        return remove;
    }

    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueueForWaitNotify queue = new MyBlockingQueueForWaitNotify(5, new LinkedList<Object>());

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    queue.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
        TimeUnit.SECONDS.sleep(2);

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                try {
                    queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"t2").start();

    }
}
